package playground.fs.rnkrsoft;

/*-
 * #%L
 * A File Scanner App
 * %%
 * Copyright (C) 2017 - 2020 OSGL (Open Source General Library)
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

import playground.fs.LogFileScanner;

import java.io.File;
import java.io.FileFilter;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Created by test on 2020/3/6.
 */
public class CatLogFileScanner implements LogFileScanner {
    @Override
    public List<String> doScan(File logFileDir, String keyword) throws Exception {
        //1.读取目录下的所有是文件的内容
        File[] files = logFileDir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                //file && xxxx.log .log
                return pathname.isFile() && pathname.getName().endsWith(".log");
            }
        });
        Future<FindTaskResult>[] futures = new Future[files.length];
        //2.构建一个线程池
        ExecutorService executor = Executors.newCachedThreadPool();
        int index = 0;
        Map<String, Integer> map = new ConcurrentHashMap<String, Integer>();
        for (File file : files) {
            //2.1提交线程池执行查找任务
            futures[index++] = executor.submit(new FindTask(file, keyword, map));
        }
        //3.等待所有任务结束后的结果
        for (Future<FindTaskResult> future : futures) {
            future.get();
        }
        //4.对结果进行排序
        ResultSort resultSort = new ResultSort();
        executor.shutdownNow();
        FindTaskResult result = new FindTaskResult();
        result.getResult().putAll(map);
        return resultSort.sort(result);
    }
}
